package com.apex.restful.service.impl;

import com.apex.common.util.DateFormatUtils;
import com.apex.entity.Tuser;
import com.apex.restful.domain.*;
import com.apex.restful.entity.TBsdtDictionary;
import com.apex.restful.entity.TBsdtTechnological;
import com.apex.restful.entity.TBsdtUserEvaluateServer;
import com.apex.restful.entity.TBsdtUserTechnological;
import com.apex.restful.service.LoginService;
import com.apex.restful.service.TSequenceService;
import com.apex.restful.service.TechnologicalService;
import com.apex.security.api.entity.TBsdtUserEvaluateDao;
import com.apex.util.DictionaryConfig;
import com.apex.util.ResponseMessage;
import com.edu.orm.datasource.DBUtil;
import com.edu.orm.entity.Pager;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 服务查询
 */
@Service
public class TechnologicalServiceImpl implements TechnologicalService {

    private static final Logger logger = LoggerFactory.getLogger(TechnologicalServiceImpl.class);

    @Autowired
    private DBUtil dbUtil;


    @Autowired
    private TechnologicalProcessRepository repository;

    @Autowired
    private UserLoginDomain loginDomain;

    @Autowired
    private DictionaryRepository dictionaryRepository;

    @Autowired
    private UserTechnologicalRepository technologicalRepository;

    @Autowired
    private UserEvaluateRepository userEvaluateRepository;

    @Autowired
    private DictionaryConfig config;

    @Autowired
    private TSequenceService sequenceService;

    private static String sql = "select t.id,t.name,t.fwtp,to_char(t.cjsj,'yyyy/MM/dd HH24:mi')as cjsfFmt,t.fwdx_Name as fwdxName,n.fwpj," +
            "(select m.name from t_bsdt_dictionary m where m.id =t.type) as fwlxFmt from t_bsdt_technological t " +
            "left join(select s.server_id,round(avg(s.fwpf))as fwpj " +
            "from t_bsdt_user_evaluate_server s group by s.server_id)n on n.server_id=t.id ";
    private static String sql_ = " left join(select s.server_id,s.userid from t_bsdt_user_technological s  group by s.server_id,s.userid)f on f.server_id=t.id ";

    /**
     * 查询全部服务
     *
     * @return
     */
    @Override
    public String getAllList() {
        List<TBsdtTechnological> list = dbUtil.getAllBeanList(sql + " where t.state =1 order by t.cjsj desc", TBsdtTechnological.class);
        Map<String, Object> map = ResponseMessage.getTrueMap();
        map.put("dataList", list);
        return JsonStream.serialize(map);
    }

    /**
     * 根据用户账号，查询与用户身份相关的全部服务
     *
     * @param userID
     * @return
     */
    @Override
    public String getAllListByUserId(String userID) {
        Map<String, Object> map = ResponseMessage.getMap();
        if (StringUtils.isNotBlank(userID)) {
            List<Tuser> tusers = loginDomain.findAllByUseridOrLogincode(userID,userID);
            if (null != tusers && tusers.size() > 0) {
                Tuser tuser = tusers.get(0);
                List<TBsdtDictionary> dictionaryList = null;
                if (null != tuser.getYhsf() && 2 == tuser.getYhsf()) {//教师
                    dictionaryList = dictionaryRepository.findByCode(config.getTeacher());
                } else {//学生
                    dictionaryList = dictionaryRepository.findByCode(config.getStudent());
                }
                if (null != dictionaryList && dictionaryList.size() > 0) {
                    TBsdtDictionary dictionary = dictionaryList.get(0);
                    List<TBsdtTechnological> list = dbUtil.getAllBeanList(sql + "where t.state =1 and ','||t.fwdx like ? order by t.cjsj desc", TBsdtTechnological.class, "%," + dictionary.getId() + ",%");
                    map = ResponseMessage.getTrueMap();
                    map.put("dataList", list);
                }
            }
        }
        return JsonStream.serialize(map);
    }

    /**
     * 根据服务编号，查询服务详情
     *
     * @param id
     * @return
     */
    @Override
    public String getEntityById(String userID, Long id) {
        Map<String, Object> map = ResponseMessage.getMap();
        if (null != id) {
            TBsdtTechnological tBsdtTechnological = repository.findOne(id);
            long ff = 0;
            Long fwl = tBsdtTechnological.getFwl();
            if (null != fwl) {
                ff = fwl;
            }
            tBsdtTechnological.setFwl(ff + 1);
            repository.save(tBsdtTechnological);
            if (null != tBsdtTechnological) {
                tBsdtTechnological.setFwlxFmt(tBsdtTechnological.getBsdtDictionary() == null ? null : tBsdtTechnological.getBsdtDictionary().getName());
                tBsdtTechnological.setBsdtDictionary(null);
                try {
                    tBsdtTechnological.setCjsfFmt(tBsdtTechnological.getCjsj() == null ? null : DateFormatUtils.formatDate(tBsdtTechnological.getCjsj(), "yyyy/MM/dd HH:mm"));
                } catch (ParseException e) {
                    logger.error("日期格式化错误：" + e.getLocalizedMessage());
                    e.printStackTrace();
                }
                tBsdtTechnological.setCjsj(null);
                if (StringUtils.isNotBlank(userID)) {
                    List<TBsdtUserTechnological> list = technologicalRepository.findByUseridAndServerId(userID, id);
                    if (null != list && list.size() > 0) {
                        tBsdtTechnological.setSfdy(1);
                    } else {
                        tBsdtTechnological.setSfdy(0);
                    }
                    List<TBsdtUserEvaluateServer> evaluateServerList = userEvaluateRepository.findByUseridAndServerId(userID, id);
                    if (null != evaluateServerList && evaluateServerList.size() > 0) {
                        tBsdtTechnological.setEvaluateDao(evaluateServerList.get(0));
                    }
                }
                if (null != tBsdtTechnological.getZgbm()) {
                    TBsdtDictionary dictionary = dictionaryRepository.findOne(tBsdtTechnological.getZgbm());
                    if (null != dictionary) {
                        tBsdtTechnological.setZgbmFmt(dictionary.getName());
                    }
                }
                map = ResponseMessage.getTrueMap();
                map.put("data", tBsdtTechnological);
            }
        }
        return JsonStream.serialize(map);
    }

    /**
     * 查询用户订阅服务
     *
     * @param code
     * @return
     */
    @Override
    public String getAllDyByUserId(String code, String userId) {
        Map<String, Object> map = ResponseMessage.getMap();
        Pager pager = null;
        if (StringUtils.isNotBlank(code) || StringUtils.isNotBlank(userId)) {
            Any any = null;
            if (StringUtils.isNotBlank(code)) {
                any = JsonIterator.deserialize(code);
            }
            String userID = "";
            String anyPage = "";
            if (null != any) {
                userID = any.get("userID").toString();
                anyPage = any.get("pager").toString();
            }
            if (StringUtils.isNotBlank(anyPage) && !"null".equals(anyPage)) {
                pager = any.get("pager").as(Pager.class);
            }
            if (StringUtils.isBlank(userID)) {
                userID = userId;
            }
            if (StringUtils.isNotBlank(userID)) {
                List<Tuser> tusers = loginDomain.findAllByUseridOrLogincode(userID,userID);
                if (null != tusers && tusers.size() > 0) {
                    Tuser tuser = tusers.get(0);
                    List<TBsdtTechnological> list = null;
                    String codes = tuser.getLogincode();
                    if (StringUtils.isBlank(codes)) {
                        codes = userID;
                    }
                    if (null == pager) {
                        list = dbUtil.getAllBeanList(sql + sql_ + "where t.state=1 and( f.userid = ? or f.userid = ?  )", TBsdtTechnological.class, userID, codes);
                    } else {
                        list = dbUtil.getAllPagerBeanList(pager, sql + sql_ + "where t.state=1 and( f.userid = ? or f.userid = ? )", TBsdtTechnological.class, userID, codes);
                    }
                    map = ResponseMessage.getTrueMap();
                    map.put("dataList", list);
                }

            }
        }
        return JsonStream.serialize(map);
    }

    @Override
    public String getAllHotServer(String code) {
        Map<String, Object> map = ResponseMessage.getMap();
        if (StringUtils.isNotBlank(code)) {
            Any any = JsonIterator.deserialize(code);
            String pager = any.get("pager").toString();
            Pager pager1 = null;
            if (StringUtils.isNotBlank(pager)) {
                pager1 = any.get("pager").as(Pager.class);
            }
            if (null == pager) {
                pager1 = new Pager();
                pager1.setCurrent(1);
                pager1.setRows(8);
            }
            List<TBsdtTechnological> list = dbUtil.getAllPagerBeanList(pager1, sql + " where t.state =1 order by t.fwl desc", TBsdtTechnological.class);
            map = ResponseMessage.getTrueMap();
            map.put("dataList", list);
        }
        return JsonStream.serialize(map);
    }

    /**
     * 用户订阅服务
     *
     * @param userID
     * @param id
     * @return
     */
    @Override
    public String updateEntity(String userID, Long id) {
        Map<String, Object> map = ResponseMessage.getMap();
        if (StringUtils.isNotBlank(userID) && null != id) {
            List<TBsdtUserTechnological> list = technologicalRepository.findByUseridAndServerId(userID, id);
            if (null == list || list.size() == 0) {
                TBsdtUserTechnological tBsdtTechnological = new TBsdtUserTechnological();
                tBsdtTechnological.setId(sequenceService.returnId(tBsdtTechnological.getClass().getSimpleName()));
                try {
                    tBsdtTechnological.setDysj(DateFormatUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm:ss"));
                } catch (ParseException e) {
                    logger.error("时间格式化错误：" + e.getLocalizedMessage());
                    e.printStackTrace();
                }
                tBsdtTechnological.setServerId(id);
                tBsdtTechnological.setUserid(userID);
                technologicalRepository.save(tBsdtTechnological);
                map = ResponseMessage.getTrueMap();
            }
        }
        return JsonStream.serialize(map);
    }

    /**
     * 用户取消订阅
     *
     * @param userID
     * @param id
     * @return
     */
    @Override
    public String updateEntityQx(String userID, Long id) {
        Map<String, Object> map = ResponseMessage.getMap();
        if (StringUtils.isNotBlank(userID) && null != id) {
            List<TBsdtUserTechnological> list = technologicalRepository.findByUseridAndServerId(userID, id);
            if (null != list && list.size() > 0) {
                for (TBsdtUserTechnological technological : list) {
                    technologicalRepository.delete(technological.getId());
                }
                map = ResponseMessage.getTrueMap();
            }

        }
        return JsonStream.serialize(map);
    }

    /**
     * 用户评价
     *
     * @param evaluateDao
     * @return
     */
    @Override
    public String entityFwpj(TBsdtUserEvaluateDao evaluateDao) {
        Map<String, Object> map = ResponseMessage.getMap();
        if (null != evaluateDao && StringUtils.isNotBlank(evaluateDao.getUserid()) && null != evaluateDao.getServerId()) {
            TBsdtUserEvaluateServer evaluateServer = new TBsdtUserEvaluateServer();
            if (null != evaluateDao.getId()) {
                evaluateServer.setId(evaluateDao.getId());
            } else {
                evaluateServer.setId(sequenceService.returnId(evaluateServer.getClass().getSimpleName()));
            }
            evaluateServer.setFwpf(evaluateDao.getFwpf());
            try {
                evaluateServer.setPfsj(DateFormatUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm:ss"));
            } catch (ParseException e) {
                logger.error("时间格式化错误：" + e.getLocalizedMessage());
                e.printStackTrace();
            }
            evaluateServer.setPjnr(evaluateDao.getPjnr());
            evaluateServer.setServerId(evaluateDao.getServerId());
            evaluateServer.setUserid(evaluateDao.getUserid());
            userEvaluateRepository.save(evaluateServer);
            map = ResponseMessage.getTrueMap();
        }
        return JsonStream.serialize(map);
    }

    @Override
    public String findAllByPager(String code) {
        Map<String, Object> map = ResponseMessage.getMap();
        if (StringUtils.isNotBlank(code)) {
            List<TBsdtTechnological> list = null;
            Any any = JsonIterator.deserialize(code);
            Pager pager = null;
            String fwlx = any.get("type").toString();
            String fwdx = any.get("fwdx").toString();
            String fwfs = any.get("fwfs").toString();
            String zgbm = any.get("zgbm").toString();
            String name = any.get("name").toString();
            StringBuffer buffer = new StringBuffer();
            buffer.append(sql);
            buffer.append(" where t.state=1 ");
            List<Object> parame = new ArrayList<>();
            if (StringUtils.isNotBlank(fwlx) && !"null".equals(fwlx)) {
                buffer.append("and t.type = ? ");
                parame.add(Long.parseLong(fwlx));
            }
            if (StringUtils.isNotBlank(fwdx) && !"null".equals(fwdx)) {
                buffer.append(" and  ','||t.fwdx like ? ");
                parame.add("%," + fwdx + ",%");
            }
            if (StringUtils.isNotBlank(fwfs) && !"null".equals(fwfs)) {
                buffer.append(" and t.fwfs = ? ");
                parame.add(Long.parseLong(fwfs));
            }
            if (StringUtils.isNotBlank(zgbm) && !"null".equals(zgbm)) {
                buffer.append(" and t.zgbm = ? ");
                parame.add(Long.parseLong(zgbm));
            }
            if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
                buffer.append(" and t.name like ? ");
                parame.add("%" + name + "%");
            }
            String pj = any.get("pager").toString();
            if (StringUtils.isNotBlank(pj) && !"null".equals(pager)) {
                pager = any.get("pager").as(Pager.class);
            }
            buffer.append(" order by t.cjsj desc ");
            if (null != pager) {
                list = dbUtil.getAllPagerBeanList(pager, buffer.toString(), TBsdtTechnological.class, parame.toArray());
            } else {
                list = dbUtil.getAllBeanList(buffer.toString(), TBsdtTechnological.class, parame.toArray());
            }
            map = ResponseMessage.getTrueMap();
            map.put("dataList", list);
        }
        return JsonStream.serialize(map);
    }
}
